import { defineStore } from 'pinia'
import { ref } from 'vue'
import { http } from '@/utils/request'

export const useTradeLogStore = defineStore('tradeLog', () => {
  const loading = ref(false)
  const logs = ref([])
  const pagination = ref({
    page: 1,
    size: 20,
    total: 0
  })

  const dailyStats = ref([])

  const fetchTradeLogs = async (params = {}) => {
    loading.value = true
    try {
      const query = {
        page: params.page || pagination.value.page,
        size: params.size || pagination.value.size,
        accountId: params.accountId,
        accountConfigId: params.accountConfigId,
        startDate: params.startDate,
        endDate: params.endDate
      }
      const response = await http.get('/trade-logs', query)
      const { list, total, page, size } = response.data
      logs.value = list || []
      pagination.value.total = total || 0
      pagination.value.page = page || 1
      pagination.value.size = size || 20
      return response.data
    } finally {
      loading.value = false
    }
  }

  const fetchDailyStats = async (params = {}) => {
    const query = {
      accountId: params.accountId,
      accountConfigId: params.accountConfigId,
      startDate: params.startDate,
      endDate: params.endDate
    }
    const response = await http.get('/stats/trade/daily', query)
    dailyStats.value = response.data || []
    return dailyStats.value
  }

  const clearLogs = () => {
    logs.value = []
    pagination.value = {
      page: 1,
      size: 20,
      total: 0
    }
  }

  return {
    loading,
    logs,
    pagination,
    dailyStats,
    fetchTradeLogs,
    fetchDailyStats,
    clearLogs
  }
})
